import * as Phaser from "phaser";
import {ProgressBarOptions} from "@/sys/models.ts";

// 进度条类（可复用）
export class ProgressBar {
    scene: Phaser.Scene;
    x: number;
    y: number;
    maxWidth: number;
    height: number;
    radius: number;
    bgColor: number;
    fgColor: number;
    strokeColor: number;
    strokeWidth: number;
    bg: Phaser.GameObjects.Graphics;
    fg: Phaser.GameObjects.Graphics;

    constructor(scene: Phaser.Scene, x: number, y: number, maxWidth: number, height: number, radius: number, options: ProgressBarOptions) {
        this.scene = scene;
        this.x = x;
        this.y = y;
        this.maxWidth = maxWidth;
        this.height = height;
        this.radius = radius;

        // 配置项
        this.bgColor = options.bgColor || 0x666666;
        this.fgColor = options.fgColor || 0x00FF00;
        this.strokeColor = options.strokeColor || 0x1DEAFF;
        this.strokeWidth = options.strokeWidth || 0;

        // 创建背景层
        this.bg = this.createRoundedRect(
            maxWidth,
            this.bgColor,
            this.strokeColor,
            this.strokeWidth
        );

        // 创建前景层（初始宽度为0）
        this.fg = this.createRoundedRect(
            0,
            this.fgColor,
            this.strokeColor,
            this.strokeWidth
        );

        this.setProgress(0); // 初始进度
    }

    // 创建圆角矩形（私有方法）
    createRoundedRect(width: number, fillColor: number, strokeColor: number, strokeWidth: number) {
        const graphics = this.scene.add.graphics()
            .setPosition(this.x, this.y);

        graphics.fillStyle(fillColor, 1);
        graphics.lineStyle(strokeWidth, strokeColor, 1);

        const actualRadius = Math.min(this.radius, width / 2, this.height / 2);

        // 绘制路径
        graphics.beginPath();
        graphics.moveTo(actualRadius, 0);

        // 右侧直线（动态宽度）
        graphics.lineTo(width - actualRadius, 0);
        graphics.arc(width - actualRadius, actualRadius, actualRadius, -Math.PI / 2, 0);

        graphics.lineTo(width, this.height - actualRadius);
        graphics.arc(width - actualRadius, this.height - actualRadius, actualRadius, 0, Math.PI / 2);

        graphics.lineTo(actualRadius, this.height);
        graphics.arc(actualRadius, this.height - actualRadius, actualRadius, Math.PI / 2, Math.PI);

        graphics.lineTo(0, actualRadius);
        graphics.arc(actualRadius, actualRadius, actualRadius, Math.PI, Math.PI * 1.5);

        graphics.closePath();
        graphics.strokePath();
        graphics.fillPath();

        return graphics;
    }

    // 设置进度（0-1）
    setProgress(ratio: number) {
        ratio = Phaser.Math.Clamp(ratio, 0, 1);
        const newWidth = this.maxWidth * ratio;

        // 销毁旧图形
        this.fg.destroy();

        // 重绘新图形
        this.fg = this.createRoundedRect(
            newWidth,
            this.fgColor,
            this.strokeColor,
            this.strokeWidth
        );
    }
}